package com.atguigu.producer;

import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.clients.producer.RecordMetadata;

import java.util.Properties;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

/**
 * create by Shipeixin on  2021-05-26  10:59
 */
public class PartitionProducer {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
//创建配置信息
        Properties properties = new Properties();

        properties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "192.168.10.103:9092");
        properties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer");
        properties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer");

        // 注册自定义分区              partitioner.class
        properties.put(ProducerConfig.PARTITIONER_CLASS_CONFIG, "com.atguigu.partition.MyPartition");


        KafkaProducer<String, String> producer = new KafkaProducer<String, String>(properties) ;



        /**
        *   此处的 future 是send线程发送消息后返回的，调用给 future的 get方法，会阻塞之前的线程，也就是main线程
         *   这样，直至send线程工作结束，main线程才会被重新唤起
         *   这样就达到了kafka同步发送消息的效果
         *     一个分区 + 消息同步发送   =  kafka中的顺序和producer的发送顺序完全一致
        * */

        for (int i = 0; i < 10; i++){
            Future<RecordMetadata> future = producer.send(new ProducerRecord<>("third", "atguigu" + 1), (metadata, exception) -> {
                if (exception == null) {
                    System.out.println("partition :" + metadata.partition() + "  " + "offset:" + metadata.offset());
                } else {
                    System.out.println(exception.getMessage());
                    exception.printStackTrace();
                }
            });

            //future.get();
        }

        producer.close();
    }
}
